//
//  LSFCycleView.swift
//  hoonpay
//
//  Created by 李胜锋 on 2017/8/2.
//  Copyright © 2017年 李胜锋. All rights reserved.
//

import UIKit

/*  使用实例
func test() {
    var banners = [Any]() //数据源
    var bannerView = LSFCycleView.init(frame: CGRect.init(x: 0, y: 0, width: 375, height: 110))
    bannerView.isShowPageControl = true //是否显示pageControl
    bannerView.direction = .horizontal  //设置滚动方向
 
     //设置item数量
    bannerView.numberOfCellBlock = {
        return banners.count
    }
 
     //返回item
    bannerView.cellBlock = {
        let imageView = UIImageView.init()
        return imageView
    }
 
     //更新item的UI、数据源
    bannerView.updateCellBlock = { (index, cell) in
        let imageView = cell as! UIImageView
        let imageUrl = banners[index]
        imageView.af_setImage(withURL: URL.init(string: imageUrl)!)
    }
 
     //item点击事件
    bannerView.selectBlock = { (index) in
        let ad = banners[index]
    }
    
    //刷新数据
    bannerView.reloadData()
}
// */


///滚动方向
enum ScrollDirection  {
    ///水平
    case horizontal
    ///垂直
    case vertical
}

 
/// 轮播图
class LSFCycleView: UIView {
    
    
    //滚动方向
    public var direction:ScrollDirection = .vertical
   
    //数据相关block
    public var selectBlock: ((_ index:Int)->Void )?
    public var updateCellBlock:((_ index:Int, _ cell:UIView) -> Void)?
    public var cellBlock:( () -> UIView)?
    public var numberOfCellBlock:(() -> Int)?
    

    
    
    //    自动滚动定时器
    private var autoScrollTimer:Timer?
    var scrollView:UIScrollView?
    var forwordView, currentView, nextView : UIView?
    var pageControl:UIPageControl?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    
    
    ///show pageControl
    var isShowPageControl:Bool = false{
        didSet {
            pageControl?.removeFromSuperview()
            pageControl = nil
            
            if isShowPageControl {
                configPageControl()
            }
        }
    }
    
    private var dataCount:Int = 0
    private var forwordIndex:Int = -1
    private var nextIndex:Int = 1
    var currentIndex:Int = 0{
        didSet {
            
            if dataCount > 0 {
                if currentIndex <= -1 {
                    currentIndex = dataCount - 1
                }
                else if currentIndex >= dataCount {
                    currentIndex = 0
                }
                
                forwordIndex = currentIndex - 1
                if currentIndex == 0 {
                    forwordIndex = dataCount - 1
                }
                
                nextIndex = currentIndex + 1
                if currentIndex == dataCount - 1 {
                    nextIndex = 0
                }
                
                
                updateCellBlock?(currentIndex, currentView!)
                updateCellBlock?(forwordIndex, forwordView!)
                updateCellBlock?(nextIndex, nextView!)
                
            
                pageControl?.currentPage = currentIndex
            }
            
        }
    }
    
    
    
// MARK:-  UI 初始化
    func setup() {
        configScrollView()
    }
    
//    初始化scrollView
    private func configScrollView() {
        scrollView = UIScrollView.init()
        scrollView?.delegate = self
        scrollView?.isPagingEnabled = true
        scrollView?.bounces = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.showsVerticalScrollIndicator = false
        self.addSubview(scrollView!)
        
        if #available(iOS 11, *) {
            scrollView?.contentInsetAdjustmentBehavior = .never
        }
    }
    
    
    private func clear() {
        forwordView?.removeFromSuperview()
        forwordView = nil
        
        currentView?.removeFromSuperview()
        currentView = nil
        
        nextView?.removeFromSuperview()
        nextView = nil
    }
    private func configCellViews() {
        clear()
        
        
        assert(cellBlock != nil, "cellBlock 不能为空")
        
        forwordView = cellBlock!()
        currentView = cellBlock!()
        nextView = cellBlock!()
        
        
        forwordView?.clipsToBounds = true
        currentView?.clipsToBounds = true
        nextView?.clipsToBounds = true
        
        currentView?.isUserInteractionEnabled = true
        let currentTap = UITapGestureRecognizer.init(target: self, action: #selector(LSFCycleView.currentTap))
        currentView?.addGestureRecognizer(currentTap)
        
        scrollView?.addSubview(forwordView!)
        scrollView?.addSubview(currentView!)
        scrollView?.addSubview(nextView!)
    }
    
    
    private func configPageControl() {
        pageControl = UIPageControl.init()
        pageControl?.currentPageIndicatorTintColor = UIColor.white;
        pageControl?.tintColor = UIColor.init(white: 1, alpha: 0.5)
        
        self.addSubview(pageControl!)
    }
    
    @objc func currentTap() {
        selectBlock?(currentIndex)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    public func reloadData() {
        configCellViews()
        layoutSubviews()
        
        guard numberOfCellBlock != nil else {
            return
        }
        
        assert(numberOfCellBlock != nil, "numberOfCellBlock 不能为空")
        dataCount = numberOfCellBlock!()
        
        self.currentIndex = 0
        self.pageControl?.numberOfPages = dataCount
        run()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let size = self.frame.size
        
        switch direction {
        //垂直方向
        case .vertical:
            scrollView?.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
            scrollView?.contentSize = CGSize.init(width: size.width, height: size.height * 3)
            
            forwordView?.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
            currentView?.frame = CGRect.init(x: 0, y: size.height, width: size.width, height: size.height)
            nextView?.frame = CGRect.init(x: 0, y: size.height * 2, width: size.width, height: size.height)
            
        //水平方向
        default:
            scrollView?.frame       = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
            scrollView?.contentSize = CGSize.init(width: size.width * 3, height: size.height)
            
            forwordView?.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
            currentView?.frame = CGRect.init(x: size.width, y: 0, width: size.width, height: size.height)
            nextView?.frame    = CGRect.init(x: size.width * 2, y: 0, width: size.width, height: size.height)
        }
        
        pageControl?.center = CGPoint.init(x: size.width / 2.0, y: size.height - 30)
        
    }

    
    
    
    // MARK: - 定时器事件
    func run() {
        stop()
        
        autoScrollTimer = Timer.scheduledTimer(timeInterval: 2.5, target: self, selector: #selector(LSFCycleView.onTimer), userInfo: nil, repeats: true)
    }
    
    func stop() {
        if autoScrollTimer != nil {
            autoScrollTimer?.invalidate()
            autoScrollTimer = nil
        }
    }
    
    @objc func onTimer() {
        
        UIView.animate(withDuration: 0.6, animations: { [weak self] in
            if let strongSelf = self {
                //垂直
                if self?.direction == .vertical {
                    strongSelf.scrollView?.setContentOffset(CGPoint.init(x: 0, y: strongSelf.frame.size.height * 2), animated: false)
                }
                else {
                   strongSelf.scrollView?.setContentOffset(CGPoint.init(x: strongSelf.frame.size.width * 2, y: 0), animated: false)
                }
            }
        }) { [weak self] (finished) in
            if let strongSelf = self {
                //垂直
                if self?.direction == .vertical {
                    strongSelf.scrollView?.setContentOffset(CGPoint.init(x: 0, y: strongSelf.frame.size.height), animated: false)
                }
                    //水平
                else {
                    strongSelf.scrollView?.setContentOffset(CGPoint.init(x: strongSelf.frame.size.width, y: 0), animated: false)
                }
                self?.currentIndex += 1
            }
        }
        
    }

}

//MARK:- scrollView代理事件
extension LSFCycleView :UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        var tempIndex = 0
        
        switch direction {
            //垂直
        case .vertical:
            tempIndex = Int(scrollView.contentOffset.y / self.frame.size.height)
            scrollView.setContentOffset(CGPoint.init(x: 0, y: self.frame.size.height), animated: false)
            
            //水平
        default:
            tempIndex = Int(scrollView.contentOffset.x / self.frame.size.width)
            scrollView.setContentOffset(CGPoint.init(x: self.frame.size.width, y: 0), animated: false)
        }
        
        if tempIndex == 2 {
            self.currentIndex += 1
        }
        else if  tempIndex == 0 {
            self.currentIndex -= 1
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.run()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.stop()
    }
}
